package com.cjym.GateWay.filters;

import com.cjym.GateWay.interfaces.TokenAuth;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * <p>令牌过滤器</p>
 *
 * @author cjym
 * @date 2023/09/15
 */
@Component
@Slf4j
@ConditionalOnProperty(name = "gateway.token.enable", havingValue = "true")
public class TokenFilter implements GlobalFilter, Ordered {
    @Value("${gateway.token.auth.impl:#{'defaultTokenAuthImpl'}}")
    private String impl;

    @Resource
    private ApplicationContext context;

    /**
     * token过滤器，过滤非法的token请求
     *
     * @param exchange
     * @param chain
     * @return 过滤器
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        //获取请求中的token

        TokenAuth tokenAuth = null;
        Object bean = context.getBean(impl);
        if (bean instanceof TokenAuth) tokenAuth = (TokenAuth) bean;
        else log.error("token实现类错误:{}", impl);
        if (tokenAuth != null && tokenAuth.tokenAuth(request)) {
            return chain.filter(exchange);
        }
        log.error("请求已被拦截");
        exchange.getResponse().setRawStatusCode(401);
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }

    /**
     * 设置优先级
     *
     * @return 优先级
     */
    @Override
    public int getOrder() {
        //设置过滤器优先级
        return 1;
    }

    @PostConstruct
    public void init() {
        log.info("初始化token过滤器完成");
    }
}
